package com.agileai.portal.controller.auth;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.SimpleHandler;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.SecurityAuthorizationConfig;
import com.agileai.portal.bizmoduler.auth.SecurityGroupManage;
import com.agileai.portal.extend.uui.UserSyncHelper;
import com.agileai.portal.wsclient.uui.ResultStatus;
import com.agileai.portal.wsclient.uui.UserSync;
import com.agileai.util.CryptionUtil;

/**
 * generated by miscdp
 */
public class ResetPasswordHandler extends SimpleHandler{
	public ResetPasswordHandler(){
		super();
	}
	
	public ViewRenderer prepareDisplay(DataParam param) {
		String userId = param.get("USER_ID");
		DataParam queryParam = new DataParam("USER_ID",userId);
		SecurityGroupManage groupManage = this.lookupService(SecurityGroupManage.class);
		DataRow row = groupManage.getContentRecord("SecurityUser", queryParam);
		String userCode = row.stringValue("USER_CODE");
		this.setAttribute("userCode",userCode);
		return new LocalRenderer(getPage());
	}
	
	@PageAction
	public ViewRenderer resetPassword(DataParam param){
		String responseText = FAIL;
		String userCode = param.get("userCode");
		SecurityAuthorizationConfig authorizationConfig = this.lookupService(SecurityAuthorizationConfig.class);
		String newUserPwd = param.get("newUserPwd");

		boolean continueTag = true;
		if (UserSyncHelper.isEnableUserInfoSync()){
			continueTag = this.modifyRemotePassword(userCode,newUserPwd);
		}
		if (continueTag){
			String encryptPwd = CryptionUtil.md5Hex(newUserPwd);
			authorizationConfig.modifyUserPassword(userCode, encryptPwd);
			responseText = SUCCESS;				
		}else{
			responseText = FAIL;
		}
		return new AjaxRenderer(responseText);
	}
    
	private boolean modifyRemotePassword(String userId,String userPwd){
    	boolean result = false;
    	try {
    		UserSync userSync = UserSyncHelper.getUserSyncService();
    		String tokenId = UserSyncHelper.genTokenId("modifyPassword");
    		ResultStatus resultStatus = userSync.modifyPassword(tokenId, userId, userPwd);
    		result = resultStatus.isSuccess();
		} catch (Exception e) {
			result = false;
			log.error(e.getLocalizedMessage(), e);
		}
    	return result;
    }	
}
